package com.spirng.leetcode.day03;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class FourSum18 {
    public static void main(String[] args) {
        fourSum(new int[]{-2,-1,-1,1,1,2,2},0);
    }
    public static List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> result=new ArrayList<>();
        Arrays.sort(nums);
        for (int k = 0; k < nums.length; k++) {
            if(target<nums[k]&&target>0){
                return result;
            }
            //对k去重
            if(k>0&&nums[k]==nums[k-1]){
                continue;
            }
            for (int i = k+1; i < nums.length; i++) {
                if(nums[k]+nums[i]>target&&nums[i]>0){
                    return result;
                }
                //对i去重
                if(i>k+1&&nums[i]==nums[i-1]){
                    continue;
                }
                int left=i+1;
                int right= nums.length-1;
                while (left<right){
                    int sum=nums[k]+nums[i]+nums[left]+nums[right];
                    if(sum>target){
                        right--;
                    }else if (sum<target){
                        left++;
                    }else {
                        result.add(Arrays.asList(nums[k],nums[i],nums[left],nums[right]));
                        while (left<right&&nums[left]==nums[left+1]) left++;
                        while (left<right&&nums[right]==nums[right-1]) right--;
                        left++;
                        right--;
                    }
                }
            }
        }
        return result;
    }
}
